<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Groups/classes/PhpFox_ComponentEditGroup.class.php, $Author:  $ */



/** Component for edit group
 * @version $Id: PhpFox_ComponentEditGroup.class.php
 *  Max Kovrigovich
 * @package module.groups
 */
class PhpFox_Mod_Groups_ComponentEditGroup extends BaseComponent
{
    /** Processing method
     */

    function process()
    {
    	App::membersOnly();

        //check permissions
        $oSecurityService = App::getModuleService('Account', 'Security');

		/* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
		$oSecurityService->checkPerm('groups', array('full'));

        $oGroupsService = $this->_oModule->getService('Groups');
        /* @var $oGroupsService PhpFox_Mod_Groups_ServiceGroups */

        $oGroupGalleryItem = $this->_oModule->getItem('GroupGallery');
        /* @var $GroupGalleryItem PhpFox_Mod_Groups_GalleryItem */

        $oSecurityService = &App::getModuleService('Account', 'Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */

        $oGalleryService = $this->_oModule->getService('Gallery');
         /* @var $oGalleryService PhpFox_Mod_Groups_ServiceGallery */

        App::loadClass('file/Image');
        $oImage = &new file_Image();

        App::loadClass('Validator');

        $aErrors = array();
        $oUser = $this->getParam('user');
        $sCurrentUserLogin = $oSecurityService->getCurrentUserLogin($oSecurityService->getCurrentUser());

        $oReq = &App::getRequest();

        //Countries
        $aLocation = array();
        foreach (App::getTxtFile('country.txt') as $sVal)
        {
            $aLocation[$sVal] = $sVal;
        }
        
        //Group categories
        $aTmp = $oGroupsService->getCategories();
        $aCategories = array();
        foreach($aTmp as $aItem)
        {
        	$aCategories[$aItem['id']] = $aItem['name'];
        }

        $iGroupId = $oReq->get('id', 0);
        if($iGroupId)
            if(!($oGroupsService->isOwner($iGroupId, $oUser->aData['user']) OR App::isStaff() ))
                App::gotoUrl('public.groups');
        $sAction = $oReq->getAction();
        $bUpdated = false;

        if($sAction == '')
        {
            if ($iGroupId)
            {
                $aGroupData = $oGroupsService->getGroupData($iGroupId);
            }
            else
            {
                $aGroupData = Array(
                    'email' => $oUser->aData['email'],
                    'location' => $oUser->aData['location'],
    		        'city' => $oUser->aData['city'],
                );
            }
        }

        //validator
        $aFields = array(
   	        'val[title]'        => array('title' => App::format('Mod_Groups.form_title'), 'def' => 'required'),
   	        'val[headline]'     => array('title' => App::format('Mod_Groups.form_headline'), 'def' => 'required'),
   	        'val[email]'        => array('title' => App::format('Mod_Groups.form_email'), 'def' => 'email'),
   	        'val[type]'         => array('title' => App::format('Mod_Groups.form_type'), 'def' => 'required'),
   	        'val[open_join]'    => array('title' => App::format('Mod_Groups.form_openjoin'), 'def' => 'required'),
   	        'val[hide_group]'   => array('title' => App::format('Mod_Groups.form_hidegroup'), 'def' => 'required'),
            'val[location]'     => array('title' => App::format('Mod_Groups.form_location'), 'def' => 'required'),
	        'val[mem_invite]'   => array('title' => App::format('Mod_Groups.form_meminvite'), 'def' => 'required'),
	        'val[pub_forum]'    => array('title' => App::format('Mod_Groups.form_pubforum'), 'def' => 'required'),
	        'val[mem_image]'    => array('title' => App::format('Mod_Groups.form_memimage'), 'def' => 'required'),
	        'val[city]'         => array('title' => App::format('Mod_Groups.form_city'), 'def' => 'required'),
	        'val[text]'         => array('title' => App::format('Mod_Groups.form_text'), 'def' => 'required'),
        );
        
        $aStates = array();
        if (App::getSetting('us_states'))
        {        	
            foreach (App::getTxtFile('us_stat.txt') as $sState)
            {
                $aStates[$sState] = $sState;
            }        
        }
        
        $oValidator = &new Validator($aFields, array());

        if($sAction == 'create' || $sAction == 'edit')
        {
	        $aValue = $oReq->getArray('val');
            if (!$oValidator->isValid($oReq->getAll()))
            {
                $this->addErrors($oValidator->getErrors());
            }

            if(!$oGroupsService->isUniqueName($aValue['title'], $iGroupId))
                $this->addErrors(App::format('Mod_Groups.error_name_exist', array($aValue['title'])));

            $aErrors = $this->getErrors();
            if (!count($this->getErrors()))
            {
                if(!in_array($aValue['type'], array_keys($aCategories)) ||
                   !in_array($aValue['open_join'], array('Yes','No')) ||
                   !in_array($aValue['hide_group'], array('Yes','No')) ||
                   !in_array($aValue['location'], array_keys($aLocation)) ||
                   !in_array($aValue['mem_invite'], array('Yes','No')) ||
                   !in_array($aValue['pub_forum'], array('Yes','No')) ||
                   !in_array($aValue['mem_image'], array('Yes','No'))
                   )
                   {
                       App::gotoUrl('public.groups');
                   }
                   $bUpdated = true;
                   if(!App::getSetting('us_states'))
                   {
                   		$aValue['state'] = '';
                   		$aValue['zip'] = '';
                   }
                   if (!empty($aValue['zip']) && !is_numeric($aValue['zip']))
                   {
                   		unset($aValue['zip']);
                   }
                   
                   if($sAction == 'edit')
                   {
                       $aValue['edit'] = time();
                       $oGroupsService->updateGroupData($iGroupId, $aValue);
                       $oGroupsService->updateGroupCount();
                   }
                   if($sAction == 'create')
                   {
                        $aValue['user'] = $oUser->aData['user'];
                        $aValue['time'] = time();
                        $aValue['views'] = 0;
                        $iNewGroupId = $oGroupsService->updateGroupData(0, $aValue);
                        $oGroupsService->addGroupMember($iNewGroupId, $oUser->aData['user'], $aValue['type']);

                        if (array_key_exists('image', $_FILES))
						{
						    $oGroupGalleryItem->aData = array
						                (
						                    'user'        => $sCurrentUserLogin,
						                    'group_id'    => $iNewGroupId,
						                    'time'        => time(),
						                    'default'     => '1',
						                );
			                $iImageId = $oGroupGalleryItem->insert();
			                $oGroupsService->updateGroupCount();
			                $sDestPath = App::getParam('groups.pic.path');
			                if ($oImage->upload('image', $sDestPath, $iImageId, 'jpg'))
			                {
			                    $oImage->loadInfo($sDestPath.$iImageId.'.jpg');
			                    $oImage->makeThumbnail($sDestPath.'thumb/'.$iImageId.'.jpg', App::getSetting('upload_set_size_thumb'), App::getSetting('upload_set_size_thumb'));
			                }
			                else
			                {
			                    $oGalleryService->deleteItem($iImageId);
			                }
						}
                        App::gotoUrl('public.groups.view',array('id'=>$iNewGroupId));
                   }

                   $aGroupData = $oGroupsService->getGroupData($iGroupId);
            }

            if($sAction == 'create')
            {
                $aVal = $oReq->get('val');
                if(count($aVal))
                {
	                $aGroupData = array('email' => $aVal['email'],
	                                    'title' => $aVal['title'],
	                                    'city' => $aVal['city'],
	                                    'text' => $aVal['text'],
	                                    'headline' => $aVal['headline'],
	                                    'open_join' => $aVal['open_join'] == "Yes",
						                'hide_group' => $aVal['hide_group'] == "Yes",
						                'mem_invite' => $aVal['mem_invite'] == "Yes",
						                'pub_forum' => $aVal['pub_forum'] == "Yes",
						                'mem_image' => $aVal['mem_image'] == "Yes",
	                                    'location' => $aVal['location'],
	                                    'category_id' => isset($aVal['category_id']) ? $aVal['category_id'] : '',
	                                );
                }
            }

	        /* @var $oValidator Validator */
        }

        $bCreate = false;
        if($iGroupId == 0)
            $bCreate = true;

        if (!isset($aGroupData['open_join']))
        {
            $aGroupData['open_join'] = '';
        }
        if (!isset($aGroupData['hide_group']))
        {
            $aGroupData['hide_group'] = '';
        }
        if (!isset($aGroupData['mem_invite']))
        {
            $aGroupData['mem_invite'] = '';
        }
        if (!isset($aGroupData['pub_forum']))
        {
            $aGroupData['pub_forum'] = '';
        }
        if (!isset($aGroupData['mem_image']))
        {
            $aGroupData['mem_image'] = '';
        }

        $oTpl = $this->_oModule->getTemplate();
        $oTpl->assignSrc('sJsVal', $oValidator->makeJS());
        $oTpl->assignSrc('sJsMess', $oValidator->makeJsMess());
        $oTpl->assign(array(
            'aGroupData'     => $aGroupData,
            'aCategories'    => $aCategories,
            'iCategoryId'    => isset($aGroupData['category_id']) ? $aGroupData['category_id'] : '',
            'aLocation'      => $aLocation,
            'iLocationId'    => $aGroupData['location'],
            'bOpenJoin'      => (ucwords(strtolower($aGroupData['open_join'])) == "Yes" ? true : false),
            'bHideGroup'     => (ucwords(strtolower($aGroupData['hide_group'])) == "Yes" ? true : false),
            'bMemInvite'     => (ucwords(strtolower($aGroupData['mem_invite'])) == "Yes" ? true : false),
            'bPubForum'      => (ucwords(strtolower($aGroupData['pub_forum'])) == "Yes" ? true : false),
            'bMemImage'      => (ucwords(strtolower($aGroupData['mem_image'])) == "Yes" ? true : false),
            'bCreate'        => $bCreate,
            'iMaxImageSize'  => App::getSetting('max_upload_size'),
            'bUpdated'       => $bUpdated,
            'aErrors'        => $aErrors,
            'aStates'      => $aStates,
            'bZipState'    => App::getSetting('us_states')
        ));
        $sHtml = $oTpl->fetch('EditGroup.html');
        return $sHtml;
    }
}
?>